package com.vhuomai.store.provider;

import com.google.common.io.Files;
import com.quanyue.auto.util.KeyGenerator;
import com.vhuomai.store.entity.BaseStoreConfig;
import com.vhuomai.store.exception.StoreException;

import java.io.*;

/**
 * @author harris
 */
public class LocalStoreProvider implements StoreProvider {
    
    @Override
    public String saveFile(BaseStoreConfig config, byte[] content, String ext) throws StoreException {
        String fileName = KeyGenerator.uuid() + ext;
        return this.saveFile(config, content, fileName);
    }
    
    @Override
    public String saveFileByName(BaseStoreConfig config, byte[] content, String fileName) throws StoreException {
        fileName = "/" + config.getMerchantNo() + "/" + fileName;
        File file = new File(config.getBucket() + fileName);
        if (!file.getParentFile().exists()) {
            if (!file.getParentFile().mkdirs()) {
                throw new StoreException("创建目录失败," + config.getBucket());
            }
        }
        try {
            Files.write(content, file);
        } catch (IOException e) {
            throw new StoreException("创建文件失败," + file.getName());
        }
        return config.getDomainUrl() + "/api/file/" + fileName;
    }
    
    @Override
    public boolean fileExist(BaseStoreConfig config, String url) throws StoreException {
        String localPath = config.getBucket() + url.substring((config.getDomainUrl() + "/api/file").length());
        File file = new File(localPath);
        return file.exists();
    }
    
    @Override
    public void remove(BaseStoreConfig config, String url) throws StoreException {
        String localPath = config.getBucket() + url.substring((config.getDomainUrl() + "/api/file").length());
        File file = new File(localPath);
        if (!file.delete()) {
            throw new StoreException("删除失败");
        }
    }
    
    @Override
    public InputStream getContent(BaseStoreConfig config, String url) throws StoreException {
        try {
            String localPath = config.getBucket() + url.substring((config.getDomainUrl() + "/api/file").length());
            return new FileInputStream(localPath);
        } catch (FileNotFoundException e) {
            throw new StoreException("文件不存在");
        }
    }
}
